Published on Oct 23, 2024 Updated on Dec 22, 2024

How to Configure and Send Emails Using Multiple Email Settings in Django

To configure and send emails using both email settings in a Django project, you can follow these steps. The goal is to attempt sending an email using the first configuration and, if it fails, fallback to the second configuration.

Steps:

  • Create a custom email backend handler: You can use a custom email backend that tries to send an email with the first email configuration, and if that fails, switches to the second configuration.

  • Set up your email configurations: Add both email configurations in your settings.py, and create a function to switch between them.

  • Implement error handling in your email sending logic: Use a try-except block to catch any failure from the first attempt and then use the second configuration to resend the email.

Here’s an example implementation:

settings.py

Add both email configurations in settings.py but don't use the Django EMAIL_* variables directly because we will manage them dynamically.

#python code

# First email configuration
EMAIL_BACKEND_1 = {
    'EMAIL_HOST': 'mail.privatedomain.com',
    'EMAIL_HOST_USER': 'mail@privatedomain.com',
    'EMAIL_HOST_PASSWORD': 'YourSecretPassword',
    'EMAIL_PORT': 465,
    'EMAIL_USE_SSL': True,
    'DEFAULT_FROM_EMAIL': 'mail@privatedomain.com',
}

# Second email configuration
EMAIL_BACKEND_2 = {
    'EMAIL_HOST': 'smtp.gmail.com',
    'EMAIL_HOST_USER': 'your_email@gmail.com',
    'EMAIL_HOST_PASSWORD': 'YourSecretPassword',
    'EMAIL_PORT': 587,
    'EMAIL_USE_TLS': True,
    'DEFAULT_FROM_EMAIL': 'your_email@gmail.com',
}

Custom Email Backend Logic

Create a custom function to switch between the email settings.

email_utils.py

#python code

from django.core.mail import send_mail, get_connection
from django.core.mail.backends.smtp import EmailBackend
from django.conf import settings

def send_email_with_fallback(subject, message, recipient_list, from_email=None):
    # First attempt using EMAIL_BACKEND_1
    email_config_1 = settings.EMAIL_BACKEND_1
    email_config_2 = settings.EMAIL_BACKEND_2

    try:
        connection = EmailBackend(
            host=email_config_1['EMAIL_HOST'],
            port=email_config_1['EMAIL_PORT'],
            username=email_config_1['EMAIL_HOST_USER'],
            password=email_config_1['EMAIL_HOST_PASSWORD'],
            use_ssl=email_config_1.get('EMAIL_USE_SSL', False),
            use_tls=email_config_1.get('EMAIL_USE_TLS', False),
        )

        send_mail(subject, message, from_email or email_config_1['DEFAULT_FROM_EMAIL'], recipient_list, connection=connection)
        return "Email sent using first configuration."
    
    except Exception as e:
        print(f"Failed to send email with first configuration. Error: {e}")
        
        # Try using EMAIL_BACKEND_2
        try:
            connection = EmailBackend(
                host=email_config_2['EMAIL_HOST'],
                port=email_config_2['EMAIL_PORT'],
                username=email_config_2['EMAIL_HOST_USER'],
                password=email_config_2['EMAIL_HOST_PASSWORD'],
                use_ssl=email_config_2.get('EMAIL_USE_SSL', False),
                use_tls=email_config_2.get('EMAIL_USE_TLS', False),
            )

            send_mail(subject, message, from_email or email_config_2['DEFAULT_FROM_EMAIL'], recipient_list, connection=connection)
            return "Email sent using second configuration."

        except Exception as e2:
            print(f"Failed to send email with second configuration. Error: {e2}")
            return "Failed to send email with both configurations."

 

Usage in your views or scripts

Now, you can use this utility function wherever you need to send an email in your Django app:

#python code
from .email_utils import send_email_with_fallback

def send_email_view(request):
    subject = 'Test Subject'
    message = 'This is a test email.'
    recipient_list = ['recipient@example.com']

    result = send_email_with_fallback(subject, message, recipient_list)
    return HttpResponse(result)

Explanation:

  • The first email configuration (EMAIL_BACKEND_1) is used to attempt sending the email.
  • If it fails (raises an exception), the code catches the error and tries sending the email again using the second configuration (EMAIL_BACKEND_2).
  • If both attempts fail, it returns an appropriate failure message.

By using this approach, you'll be able to automatically failover to the second email configuration if the first one fails.